<template>
  <view class="order-container">
    <!-- 状态标签栏 -->
    <view class="status-tabs">
      <scroll-view class="tabs-scroll" scroll-x>
        <view class="tabs-list">
          <view 
            class="tab-item"
            :class="{ active: currentStatus === item.value }"
            v-for="item in statusTabs"
            :key="item.value"
            @click="handleStatusChange(item.value)"
          >
            <text class="tab-text">{{ item.label }}</text>
            <view class="tab-badge" v-if="item.count > 0">
              <text class="badge-text">{{ item.count }}</text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-section" v-if="showSearch">
      <view class="search-bar">
        <uni-search-bar 
          v-model="searchKeyword" 
          placeholder="搜索订单号或用户名"
          @confirm="handleSearch"
          @clear="handleClearSearch"
        />
      </view>
      <view class="search-filters">
        <uni-datetime-picker 
          v-model="dateRange" 
          type="daterange"
          rangeSeparator="至"
          placeholder="选择时间范围"
          @change="handleDateChange"
        />
      </view>
    </view>

    <!-- 订单列表 -->
    <scroll-view 
      class="order-list" 
      scroll-y 
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view class="list-content">
        <view 
          class="order-card"
          v-for="order in orderList"
          :key="order.id"
          @click="viewDetail(order)"
        >
          <!-- 订单头部 -->
          <view class="order-header">
            <view class="order-info">
              <text class="order-no">{{ order.order_no }}</text>
              <text class="order-time">{{ formatTime(order.created_at) }}</text>
            </view>
            <view class="order-status">
              <uni-tag 
                :text="getOrderStatusText(order)" 
                :type="getOrderStatusType(order)"
                size="small"
              />
            </view>
          </view>

          <!-- 订单内容 -->
          <view class="order-body">
            <view class="activity-info">
              <text class="activity-name">{{ order.activity_name }}</text>
              <view class="order-meta">
                <text class="meta-text">用户：{{ order.username }}</text>
                <text class="meta-text">数量：{{ order.quantity }}件</text>
              </view>
            </view>
            <view class="order-amount">
              <text class="amount-text">¥{{ formatPrice(order.amount) }}</text>
            </view>
          </view>

          <!-- 团购状态 -->
          <view class="group-status" v-if="order.group_status !== undefined">
            <view class="status-info">
              <uni-icons type="person" size="14" color="#999" />
              <text class="status-text">{{ getGroupStatusText(order.group_status) }}</text>
            </view>
          </view>

          <!-- 订单操作 -->
          <view class="order-actions" v-if="canOperate(order)">
            <button 
              class="action-btn"
              v-if="order.status === 1"
              @click.stop="confirmOrder(order)"
            >
              确认订单
            </button>
            <button 
              class="action-btn secondary"
              v-if="order.status === 0"
              @click.stop="cancelOrder(order)"
            >
              取消订单
            </button>
          </view>
        </view>

        <!-- 加载更多 -->
        <view class="load-more" v-if="hasMore">
          <uni-load-more :status="loadStatus" />
        </view>

        <!-- 空状态 -->
        <view class="empty-state" v-if="!loading && orderList.length === 0">
          <image class="empty-image" src="/static/images/empty-order.png" />
          <text class="empty-text">暂无订单数据</text>
        </view>
      </view>
    </scroll-view>

    <!-- 搜索按钮 -->
    <view class="search-fab" @click="toggleSearch" v-if="!showSearch">
      <uni-icons type="search" size="20" color="#fff" />
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { orderApi } from '@/api/groupbuy';
import type { Order, OrderQuery } from '@/types/groupbuy';

// 响应式数据
const orderList = ref<Order[]>([]);
const loading = ref(false);
const refreshing = ref(false);
const showSearch = ref(false);
const searchKeyword = ref('');
const dateRange = ref('');
const currentStatus = ref('all');
const currentPage = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);

// 状态标签配置
const statusTabs = ref([
  { label: '全部', value: 'all', count: 0 },
  { label: '待支付', value: 'pending', count: 0 },
  { label: '已支付', value: 'paid', count: 0 },
  { label: '已完成', value: 'completed', count: 0 },
  { label: '已取消', value: 'cancelled', count: 0 },
]);

// 加载状态
const loadStatus = computed(() => {
  if (loading.value) return 'loading';
  if (!hasMore.value) return 'noMore';
  return 'more';
});

// 格式化价格
const formatPrice = (price: number) => {
  return (price / 100).toFixed(2);
};

// 格式化时间
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp * 1000);
  return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 获取订单状态文本
const getOrderStatusText = (order: Order) => {
  switch (order.status) {
    case 0: return '待支付';
    case 1: return '已支付';
    case 2: return '已完成';
    case 3: return '已取消';
    default: return '未知';
  }
};

// 获取订单状态类型
const getOrderStatusType = (order: Order) => {
  switch (order.status) {
    case 0: return 'warning';
    case 1: return 'success';
    case 2: return 'info';
    case 3: return 'error';
    default: return 'default';
  }
};

// 获取团购状态文本
const getGroupStatusText = (groupStatus: number) => {
  switch (groupStatus) {
    case 0: return '拼团中';
    case 1: return '拼团成功';
    case 2: return '拼团失败';
    default: return '未知';
  }
};

// 判断是否可以操作
const canOperate = (order: Order) => {
  return order.status === 0 || order.status === 1;
};

// 加载订单列表
const loadOrderList = async (reset = false) => {
  if (loading.value) return;
  
  try {
    loading.value = true;
    
    if (reset) {
      currentPage.value = 1;
      hasMore.value = true;
    }

    const params: OrderQuery = {
      page: currentPage.value,
      pageSize: pageSize.value,
    };

    if (searchKeyword.value) {
      params.keyword = searchKeyword.value;
    }

    if (currentStatus.value !== 'all') {
      switch (currentStatus.value) {
        case 'pending':
          params.status = 0;
          break;
        case 'paid':
          params.status = 1;
          break;
        case 'completed':
          params.status = 2;
          break;
        case 'cancelled':
          params.status = 3;
          break;
      }
    }

    if (dateRange.value) {
      const dates = dateRange.value.split(' 至 ');
      if (dates.length === 2) {
        params.startTime = dates[0];
        params.endTime = dates[1];
      }
    }

    const res = await orderApi.getList(params);
    
    if (res.success) {
      const newList = res.data.list || [];
      
      if (reset) {
        orderList.value = newList;
      } else {
        orderList.value.push(...newList);
      }
      
      hasMore.value = newList.length === pageSize.value;
      
      if (!reset) {
        currentPage.value++;
      }
    } else {
      uni.showToast({
        title: res.message || '加载失败',
        icon: 'none',
      });
    }
  } catch (error) {
    console.error('加载订单列表失败:', error);
    uni.showToast({
      title: '加载失败',
      icon: 'none',
    });
  } finally {
    loading.value = false;
    refreshing.value = false;
  }
};

// 状态切换
const handleStatusChange = (status: string) => {
  currentStatus.value = status;
  loadOrderList(true);
};

// 搜索
const handleSearch = () => {
  loadOrderList(true);
};

// 清除搜索
const handleClearSearch = () => {
  searchKeyword.value = '';
  loadOrderList(true);
};

// 日期范围变化
const handleDateChange = () => {
  loadOrderList(true);
};

// 切换搜索显示
const toggleSearch = () => {
  showSearch.value = !showSearch.value;
};

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true;
  loadOrderList(true);
};

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loading.value) {
    loadOrderList();
  }
};

// 查看详情
const viewDetail = (order: Order) => {
  uni.navigateTo({
    url: `/pages/groupons/order/detail?id=${order.id}`,
  });
};

// 确认订单
const confirmOrder = (order: Order) => {
  uni.showModal({
    title: '确认订单',
    content: '确定要确认此订单吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await orderApi.updateStatus(order.id, 1);
          if (result.success) {
            uni.showToast({
              title: '确认成功',
              icon: 'success',
            });
            loadOrderList(true);
          } else {
            uni.showToast({
              title: result.message || '确认失败',
              icon: 'none',
            });
          }
        } catch (error) {
          uni.showToast({
            title: '确认失败',
            icon: 'none',
          });
        }
      }
    }
  });
};

// 取消订单
const cancelOrder = (order: Order) => {
  uni.showModal({
    title: '取消订单',
    content: '确定要取消此订单吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await orderApi.updateStatus(order.id, 3);
          if (result.success) {
            uni.showToast({
              title: '取消成功',
              icon: 'success',
            });
            loadOrderList(true);
          } else {
            uni.showToast({
              title: result.message || '取消失败',
              icon: 'none',
            });
          }
        } catch (error) {
          uni.showToast({
            title: '取消失败',
            icon: 'none',
          });
        }
      }
    }
  });
};

// 页面加载
onMounted(() => {
  // 检查是否需要显示搜索
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = (currentPage as any).options;
  
  if (options?.showSearch === 'true') {
    showSearch.value = true;
  }
  
  loadOrderList(true);
});
</script>

<style lang="scss" scoped>
.order-container {
  height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.status-tabs {
  background: #fff;
  border-bottom: 1rpx solid #f0f0f0;
  
  .tabs-scroll {
    white-space: nowrap;
    
    .tabs-list {
      display: flex;
      padding: 0 32rpx;
      
      .tab-item {
        position: relative;
        flex-shrink: 0;
        padding: 24rpx 32rpx;
        display: flex;
        align-items: center;
        gap: 8rpx;
        
        &.active {
          .tab-text {
            color: #1890FF;
            font-weight: 600;
          }
          
          &::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 40rpx;
            height: 4rpx;
            background: #1890FF;
            border-radius: 2rpx;
          }
        }
        
        .tab-text {
          font-size: 28rpx;
          color: #666;
        }
        
        .tab-badge {
          background: #FF4D4F;
          border-radius: 20rpx;
          padding: 2rpx 8rpx;
          min-width: 32rpx;
          height: 32rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          
          .badge-text {
            font-size: 20rpx;
            color: #fff;
          }
        }
      }
    }
  }
}

.search-section {
  background: #fff;
  padding: 24rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  .search-bar {
    margin-bottom: 16rpx;
  }
  
  .search-filters {
    display: flex;
    gap: 16rpx;
  }
}

.order-list {
  flex: 1;
  
  .list-content {
    padding: 24rpx 32rpx;
  }
}

.order-card {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 24rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    .order-info {
      .order-no {
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
        display: block;
        margin-bottom: 8rpx;
      }
      
      .order-time {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
  
  .order-body {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 24rpx;
    
    .activity-info {
      flex: 1;
      
      .activity-name {
        font-size: 30rpx;
        color: #333;
        display: block;
        margin-bottom: 12rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      
      .order-meta {
        display: flex;
        gap: 24rpx;
        
        .meta-text {
          font-size: 24rpx;
          color: #666;
        }
      }
    }
    
    .order-amount {
      .amount-text {
        font-size: 32rpx;
        font-weight: 600;
        color: #FF4D4F;
      }
    }
  }
  
  .group-status {
    padding: 0 24rpx 16rpx;
    
    .status-info {
      display: flex;
      align-items: center;
      gap: 8rpx;
      
      .status-text {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
  
  .order-actions {
    display: flex;
    gap: 16rpx;
    padding: 16rpx 24rpx;
    border-top: 1rpx solid #f0f0f0;
    
    .action-btn {
      flex: 1;
      height: 64rpx;
      border-radius: 8rpx;
      font-size: 26rpx;
      border: 1rpx solid #1890FF;
      background: #1890FF;
      color: #fff;
      
      &.secondary {
        background: #fff;
        color: #1890FF;
      }
    }
  }
}

.load-more {
  padding: 32rpx 0;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 120rpx 0;
  
  .empty-image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 32rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}

.search-fab {
  position: fixed;
  right: 32rpx;
  bottom: 120rpx;
  width: 96rpx;
  height: 96rpx;
  background: #1890FF;
  border-radius: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(24, 144, 255, 0.3);
  z-index: 999;
  
  &:active {
    transform: scale(0.95);
  }
}
</style>